//
//  MyOrderVC.swift
//  RPay
//
//  Created by CharlieLiao on 2017/7/8.
//  Copyright © 2017年 Charlie. All rights reserved.
//

import MJRefresh

class MyOrderVC: BaseVC, UITableViewDelegate, UITableViewDataSource, CTAPIManagerCallBackDelegate, CTAPIManagerParamSource, UISearchBarDelegate
{
    
    // MARK: - Life Cycle
    override func loadView() {
        
        view = tableView
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "MyOrderGoodsCell", bundle: nil), forCellReuseIdentifier: "CellID")
        tableView.register(UINib(nibName: "MyOrderHeadCell", bundle: nil), forCellReuseIdentifier: "CellHeadID")
        tableView.register(UINib(nibName: "MyOrderFootCell", bundle: nil), forCellReuseIdentifier: "CellFootID")
        tableView.keyboardDismissMode = .onDrag
        
        searchBar.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = LocalStr("我的订单")
        // Do any additional setup after loading the view.
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "icon_日历筛选").renderOriginal(), style: .plain, target: self, action: #selector(点击时间筛选))
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshHeader))
        tableView.mj_header.beginRefreshing()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }
    
    // MARK: - Table View Data Source
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return orders.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let order = orders[section]
        return order.detailList.count+2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let order = orders[indexPath.section]
        
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CellHeadID", for: indexPath) as! MyOrderHeadCell
            cell.orderIDLabel.text = LocalStr("订单编号：").appending(order.orderId)
            switch order.status {
            case .nonPay:
                cell.order状态Label.text = LocalStr("等待付款")
            case .didPay:
                cell.order状态Label.text = LocalStr("交易成功")
            }
            return cell
        }
            
        else if indexPath.row == order.detailList.count+1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CellFootID", for: indexPath) as! MyOrderFootCell
            
            cell.totalLabel.text = String(format: LocalStr("共%@件商品 合计：RH %@"), order.totalNumbers, order.totalAmount)
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath) as! MyOrderGoodsCell
        let goods = order.detailList[indexPath.row-1]
        cell.nameLabel.text = goods.goodsName
        cell.countLabel.text = String(format: "x%i", goods.goodsNum)
        cell.priceLabel.text = goods.perAmount
        
        return cell
    }
    
    // MARK: - Table View Delegate
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let order = orders[indexPath.section]
        
        if indexPath.row == 0 {
            return 46
        }
        else if indexPath.row == order.detailList.count+1 {
            return 42
        }
        
        return 60
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = OrderDetailVC()
        vc.order = orders[indexPath.section]
        vc.didTrashOrder = {(order: OrderModel) in
            self.orders.remove(at: indexPath.section)
        }
        navigationController!.pushViewController(vc, animated: true)
    }
    
    // MARK: - UISearchBarDelegate
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
    {
        if !tableView.mj_header.isRefreshing() {
            searchBar.resignFirstResponder()
            navigationController!.showLoading()
            refreshHeader()
        }
    }
    
    // MARK: - APIManagerParamSource
    
    func params(forApi manager: CTAPIBaseManager!) -> [AnyHashable : Any]!
    {
        var params: [String: AnyHashable] = [kApiParamPageNo: pageNo]
        // 搜索内容
        if let search = searchBar.text {
            params[kApiParamGoodsName] = search
        }
        
        if startDate != nil && endDate != nil {
            params[kApiParamStartDate] = (startDate! as NSDate).toDateString
            params[kApiParamEndDate] = (endDate! as NSDate).toDateString
        }
        
        return params
    }
    
    // MARK: - APIManagerCallBackDelegate
    
    func managerCallAPIDidSuccess(_ manager: CTAPIBaseManager!)
    {
        let model = manager.fetchData(with: OrderModelReformer()) as! OrderListModel
        
        let toTop: Bool
        
        if pageNo == 0 {
            tableView.mj_header.endRefreshing()
            navigationController?.hideLoading()
            total = model.total
            outInLabel.text = String(format: "支出 RH %@", model.amountOut == nil ? "0.00": model.amountOut)
            
            if tableView.mj_footer == nil {
                tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(refreshFooter))
            } else {
                tableView.mj_footer.resetNoMoreData()
            }
            orders.removeAll()
            toTop = true
            
        } else {
            tableView.mj_footer.endRefreshing()
            toTop = false
        }
        
        if model.content != nil {
            orders.append(contentsOf: model.content)
        }
        
        if orders.count >= total {
            tableView.mj_footer.endRefreshingWithNoMoreData()
        }
        tableView.reloadData()
        _ordersApiManager = nil
        if toTop {
            _ = tableView.scrollsToTop
        }
    }
    
    func managerCallAPIDidFailed(_ manager: CTAPIBaseManager!)
    {
        if pageNo == 0 {
            navigationController?.hideLoading()
            tableView.mj_header.endRefreshing()
        } else {
            tableView.mj_footer.endRefreshing()
        }
        alert(manager.errorMessage)
        _ordersApiManager = nil
    }
    
    // MARK: - Evnet respond
    /// 下拉刷新
    func refreshHeader() {
        pageNo = 0
        ordersApiManager.loadData()
    }
    
    /// 上拉加载
    func refreshFooter() {
        pageNo = pageNo+1
        ordersApiManager.loadData()
    }
    
    func 点击时间筛选() {
        let vc = DateSelectVC(startDate: startDate, endDate: endDate)
        vc.tapSearch = {[weak self](startDate, endDate) in
            self?.startDate = startDate
            self?.endDate = endDate
            self?.refreshHeader()
        }
        present(vc, animated: true, completion: nil)
    }
    
    // MARK: - Get / Set
    private var startDate: Date?
    private var endDate: Date?
    /// 页码
    var pageNo = 0
    /// 总条数
    var total = 0
    
    /// 数据源
    lazy var orders = [OrderModel]()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.separatorStyle = .none
        
        let header = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 62))
        header.addSubview(self.searchBar)
        header.addSubview(self.outInLabel)
        
        tableView.tableHeaderView = header
        tableView.backgroundColor = UIColor.appBackground
        return tableView
    }()
    
    lazy var searchBar: UISearchBar = {
        let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 320, height: 44))
        searchBar.searchBarStyle = .minimal
        searchBar.autoresizingMask = .flexibleWidth
        searchBar.placeholder = LocalStr("商品名搜索")
        searchBar.enablesReturnKeyAutomatically = false
        return searchBar
    }()
    
    lazy var outInLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 20, y: 44, width: 300, height: 18))
        label.textColor = UIColor.appSubText
        label.font = UIFont.appLightFont(ofPX: 13)
        return label
    }()
    
    private var _ordersApiManager: MyOrdersApiManager?
    private var ordersApiManager: MyOrdersApiManager {
        if _ordersApiManager == nil {
            _ordersApiManager = MyOrdersApiManager()
            _ordersApiManager!.delegate = self
            _ordersApiManager!.paramSource = self
        }
        return _ordersApiManager!
    }
}
